#include "tcpsocket.h"

#include <QMessageBox>
#include <QSqlTableModel>
#include <QSqlDatabase>
#include <QSqlError>
#include <QDebug>
#include <QSqlQuery>
#include <QMessageBox>

TcpSocket::TcpSocket(QObject *parent):QTcpSocket(parent)
{
    connect(this, SIGNAL(disconnected()), SLOT(slotDisconnected()));
    connect(this, SIGNAL(readyRead()), SLOT(slotReadData()));

    isSuccess = false;
    regSuccess = false;
}

TcpSocket::~TcpSocket()
{

}

void TcpSocket::slotDisconnected()
{
    emit disconnected(socketDescriptor());
}

void TcpSocket::slotReadData()
{
    while(bytesAvailable() > 0){
        QByteArray datagrame;
        datagrame.resize(bytesAvailable());
        read(datagrame.data(), datagrame.size());
        qDebug() << "in tcpsocket : " << datagrame.data();

        QString msg = QString(datagrame.data());
        qDebug() << msg;
        QStringList msgList = msg.split("#*#");

        qDebug() << "at(0) : " << msgList.at(0);
        qDebug() << "at(1) : " << msgList.at(1);

        if(msgList.count() != 2)
        {
            qDebug() << "Parament error !";
        }
        else
        {
            if(msgList.at(0) == "DATA")
            {
                qDebug() << "Data : " << msgList.at(1);
                QString temp_msg = msgList.at(1);
                QByteArray ba_msg;
                ba_msg = temp_msg.toLatin1();
                qDebug() << "ba_msg : " << ba_msg;
                emit updateMsg(ba_msg);
            }
            else if(msgList.at(0) == "REGISTER")
            {
                qDebug() << "Register infomation : " << msgList.at(1);
                QString temp_reg = msgList.at(1);
                QStringList regList = temp_reg.split("*^*");

                qDebug() << "regList at(0) : " << regList.at(0);
                qDebug() << "regList at(1) : " << regList.at(1);

                QSqlQuery reg_query;
                reg_query.exec("select * from users");

                while(reg_query.next())
                {
                    QString reg_account = reg_query.value(1).toString();
                    QString reg_password = reg_query.value(2).toString();

                    qDebug() << reg_account << " : " << reg_password;
                    if(regList.at(0) != reg_account)
                    {
                        qDebug() << "Success : " << "Register in database success .";
                        regSuccess = true;
                        //break;//just do it, do not break, to loop all;
                    }
                    else
                    {
                        qDebug() << "Error : " << "Account is exist .";
                        regSuccess = false;
                        continue;
                    }
                }
                if(regSuccess == false)
                {
                    QString ret_error = "Error";
                    write(ret_error.toLatin1(), ret_error.toLatin1().length());
                }
                else
                {
                    reg_query.last();
                    int reg_id = reg_query.value(0).toInt();
                    qDebug() << "Now ID : " << reg_id;

                    reg_query.prepare("INSERT INTO users(id, account, password)"
                                      "VALUES(:id, :account, :password)");
                    reg_query.bindValue(":id", reg_id + 1);
                    reg_query.bindValue(":account", regList.at(0));
                    reg_query.bindValue(":password", regList.at(1));

                    bool ok = reg_query.exec();
                    if(!ok)
                    {
                        qDebug() << "Error : " << "Insert into error !";
                    }
                    else
                    {
                        qDebug() << "Success : " << "Insert into success !";
                        QString ret = "Success";
                        write(ret.toLatin1(), ret.toLatin1().length());
                    }
                }
            }
            else
            {
                QSqlQuery query;
                query.exec("select * from users");
                while(query.next())
                {
                    QString account = query.value(1).toString();
                    QString password = query.value(2).toString();
                    qDebug() << account << " : " << password;
                    if(msgList.at(0) == account)
                    {
                        if(msgList.at(1) == password)
                        {
                            qDebug() << "Success : " << "Check Success";
                            isSuccess = true;
                            break;
                        }
                        else
                        {
                            qDebug() << "Error : " << "Password is not correct !";
                            isSuccess = false;
                            continue;
                        }
                    }
                    else if(msgList.at(0) != account)
                    {
                        qDebug() << "Error : " << "Account is not in the database !";
                        isSuccess = false;
                        continue;
                    }
                }
                if(true == isSuccess)
                {
                    QString ret = "Success";
                    write(ret.toLatin1(), ret.toLatin1().length());
                }
                else
                {
                    QString ret_error = "Error";
                    write(ret_error.toLatin1(), ret_error.toLatin1().length());
                }
            }
        }

        qDebug() << datagrame.data();
        //emit updateMsg(datagrame);
    }
}
